import {ref} from 'vue'
import {
	getLocation,
	defaultLatitude,
	defaultLongitude
} from '@/common/utils/map'
import { useI18n } from "vue-i18n";

export const useLocation = () => {
	const latitude = ref(defaultLatitude)
	const longitude = ref(defaultLongitude)
	const addressText = ref('')
	
	const { t } = useI18n()
	
	const getUserLocation = async (isRefresh?:boolean) => {
	
		let userGeolocation = uni.getStorageSync('userGeolocation')
		if (userGeolocation && !isRefresh) {
			latitude.value = userGeolocation.latitude
			longitude.value = userGeolocation.longitude
			addressText.value = userGeolocation.address_component.city
			
		} else {
			try{
				const res = await getLocation(t('nearby.openGPS'), t('nearby.GPSErr'))
				latitude.value = res.latitude
				longitude.value = res.longitude
				addressText.value = res.address_component.city
			}catch(e){
				//TODO handle the exception
			}
		}
	}

	return {
		latitude,
		longitude,
		addressText,
		getUserLocation
	}
}